import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import logging  
from logging.handlers import TimedRotatingFileHandler
from flask.logging import default_handler
from logging.config import dictConfig

basedir = os.path.abspath(os.path.dirname(__file__))

db = SQLAlchemy()

#日志配置
dictConfig({
    'version': 1,
    'formatters': {'default': {
				        'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
				        },
				  'standard': {
				        'format' : '%(asctime)s %(levelname)s %(module)s.%(funcName)s Line:%(lineno)d %(message)s'
				        }
    },
    'handlers': {'wsgi': {
					        'class': 'logging.StreamHandler',
					        'stream': 'ext://flask.logging.wsgi_errors_stream',
					        'formatter': 'default'
					    },

				'time_rotate_handler': {
					'level': 'INFO',
					'class': 'logging.handlers.TimedRotatingFileHandler',
					'formatter': 'standard',
					'filename': os.path.join(basedir, '../logs/garden.log'),  #输出位置
					'when': 'midnight', #分割单位
					'interval': 1,#单位长度
					'backupCount': 30,  #备份份数
					'encoding': 'utf8'  #文件编码
				},

				"size_rotate_handler": {
			            "class": "logging.handlers.RotatingFileHandler",
			            "level": "INFO",
			            "formatter": "standard",
			            "filename": os.path.join(basedir, '../logs/garden.log'),
			            "maxBytes": 1024*1024*5, #5M
			            "backupCount": 20,
			            "encoding": "utf8"
			        },

    },
    'root': {
        'level': 'INFO',
        'handlers': ['wsgi','size_rotate_handler']
    }
})

def create_app(test_config=None):
	# global db
	# 创建并配置应用
	app = Flask(__name__, instance_relative_config=True)

	#读取配置文件
	app.config.from_object('gardenConfig.Config')
	#初始化数据库
	db.init_app(app)

	# print(app.logger.handlers)
	# app.logger.removeHandler(default_handler)
	# print(app.logger.handlers)
	# hdlr = getLoggerHandler()
	# hdlr.doRollover()
	# logger = logging.getLogger()
	# print(logger.handlers)
	# if len(logger.handlers) == 0:
	# 	hdlr = getLoggerHandler()
	# 	logger.addHandler(hdlr)

	# if hdlr not in app.logger.handlers :#避免重复
	# 	app.logger.addHandler(hdlr)

	# print(hdlr in app.logger.handlers)

	# print(app.logger.handlers)
	app.config.from_mapping(
		SECRET_KEY='dev',
		DATABASE=os.path.join(app.instance_path,'garden.sqlite'),
	)

	app.config['UPLOAD_FOLDER']=os.path.join(app.static_folder,'upload')

	print('UPLOAD_FOLDER: %s' % app.config['UPLOAD_FOLDER'])

	if test_config is None:
		# 加载实例配置
		app.config.from_pyfile('config.py', silent=True)
	else:
		app.config.from_mapping(test_config)


	#确认实例文件夹存在
	try:
		os.makedirs(app.instance_path)
	except OSError:
		pass

	@app.route('/hello')
	def hello():
		return 'Hello World!'


	from garden.database import db_session
	@app.teardown_appcontext
	def shutdown_session(exception=None):
		db_session.remove()

	from . import sqlitdb
	sqlitdb.init_app(app)

	from . import auth, blog, topic, repair, discovery
	app.register_blueprint(auth.bp)
	app.register_blueprint(blog.bp)
	app.register_blueprint(topic.bp)
	app.register_blueprint(repair.bp)
	app.register_blueprint(discovery.bp)

	app.add_url_rule('/', endpoint='index')

	return app

def getLoggerHandler():
	level = logging.INFO
	filename = os.path.join(basedir, '../logs/garden.log')
	format = '%(asctime)s %(levelname)s %(module)s.%(funcName)s Line:%(lineno)d %(message)s'
	hdlr = TimedRotatingFileHandler(filename,"midnight",1,0)
	fmt = logging.Formatter(format)
	hdlr.setFormatter(fmt)
	hdlr.suffix = "%Y-%m-%d"
	hdlr.setLevel(level)
	return hdlr

